// clearTimeout(adf.mf.internal.amx._failSafeTimer);
// adf.mf.internal.amx._failSafeTimer = window.setTimeout(adf.mf.internal.amx.killLoadingIndicator,1E4);

//This is an event that fires when the user presses the device back button
document.addEventListener("showpagecomplete", onDeviceReady, false);

function onDeviceReady() {
    document.addEventListener("backbutton", backKeyDown, true);
    //document.addEventListener("touchstart", touchHandler, true);
    //document.addEventListener("touchmove", touchHandler, true);
    //document.addEventListener("touchend", touchHandler, true);
    //document.addEventListener("touchcancel", touchHandler, true); 
    methods();
}

function backKeyDown() {
    // callback to exit application on mainActivity
    if ($('#mainActivity').length) {
        adf.mf.api.invokeMethod("mobile.classes.FetchJavascript", "exitApplicationCallback", 
            // success callback
            function() {
                 console.log("backKeyDown(): Success callback Success");
            }, 
            // error callback
            function() {
                console.log("backKeyDown(): Success callback Error");
            }
        );
    
    // back on all pages without mainActivity
    } else {
        adf.mf.api.amx.doNavigation("__back");
    }
}

/*function touchHandler(event) {
    var touches = event.changedTouches,
        first = touches[0],
        type = "";

    switch(event.type) {
    case "touchstart": 
        type = "mousedown"; 
    break;
    case "touchmove":  
        type = "mousemove"; 
    break;        
    case "touchend":
    case "touchcancel":
        type = "mouseup"; 
    break;
    default: 
        return;
    }

    //initMouseEvent(type, canBubble, cancelable, view, clickCount, 
    //           screenX, screenY, clientX, clientY, ctrlKey, 
    //           altKey, shiftKey, metaKey, button, relatedTarget);

    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                          first.screenX, first.screenY, 
                          first.clientX, first.clientY, false, 
                          false, false, false, 0, null);

    first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}*/

    

methods = (function () {

    /**
     * Confirm to exit the application
     */
    exitApplication = function() {
        var cFirm = confirm("Chcete ukon\u010Dit aplikaci?");
        if (cFirm == true) {
            //Code to exit the application
            navigator.app.exitApp();
        }
    }
    
    scrollTopPanel = function() {
        //$(document).on('touchstart', 'div.amx-panelGroupLayout', function() {
            //$('.topPanel').scrollLeft(800);
            //$('.topPanel').css("background-color","red");
            //var leftPos = $('.topPanel').scrollLeft();
            
            /*$( document ).ready(function() {
                $(".topPanel").animate({scrollLeft: 2000}, 800);
              });*/
        //});
    }
    
    function getPhoneGapPath() {
        var path = window.location.pathname;
        var patha = path.substring(0, path.lastIndexOf('/') - 3);
        var regex = new RegExp('%20', 'g');
        

        if( device.platform === 'iPad' ) {
            return 'file://localhost' + patha.replace(regex, ' ');
        } else {
            return 'file://' + patha.replace(regex, ' ');
        }    
    }
    
    
   
    /**
     * Playing audio file
     * Doc: http://docs.phonegap.com/en/2.6.0/cordova_media_media.md.html
     */
    playAudio = function() {
        var file;
        // play the audio file
        // original audio files
        
        if (arguments[0].substring(0, 5) == "FARs/") {
            file = getPhoneGapPath() + arguments[0];   
            
        // custom audio files
        } else {
            file = 'file://' + arguments[0]; 
        }
        
        var media = new Media(file,
            // success callback
            function() {
                console.log("playAudio():Audio Success");
                if(media != null){
                    media.release();
                }
            },
            // error callback
            function(err) {
                console.log("playAudio():Audio Error: "+err.message + " arg: " + arguments[0]);
                console.log("File " + getPhoneGapPath()+ file);
                //alert("File " + err.message+"---"+ file);
                if(media != null){
                    media.release();
                }
            }
        );

        // play audio
        media.play();
    }
    
    /**
     * Playing audio file
     * Doc: http://docs.phonegap.com/en/2.6.0/cordova_media_media.md.html
     */
    var currentSound = 0;
    var mediaObjects = [];
    playSelectedAudio = function() {
        currentSound = 0;
        mediaObjects = [];
        
        for(var i=0;i<arguments.length;i++) {
            var file;
            // play the audio file
            // original audio files
            if (arguments[i].substring(0, 5) == "FARs/") {
                file = getPhoneGapPath() + arguments[i]; 
                
            // custom audio files
            } else {
                file = 'file://' + arguments[i]; 
            }
            //alert(arguments[i]);
            
            var media = new Media(file,
                // success callback
                playOnSuccess,
                // error callback
                function(err) {
                    console.log("playAudio():Audio Error: "+err.message + " arg: " + arguments[i]);
                    //alert("File " + err.message+"---"+ file);
                    playOnSuccess();
                }
            );
            mediaObjects.push(media);
        }
        
        if (mediaObjects[0] != null) {
            mediaObjects[0].play();
        } else {
            //alert("chyba");
        }
        
    }
    
    function playOnSuccess() {
        if(mediaObjects[currentSound] != null){
            mediaObjects[currentSound].release();
        }
        console.log("playAudio():Audio Success");
        currentSound++;
        if (currentSound < mediaObjects.length) {
            mediaObjects[currentSound].play();
        }
    }
    
    /**
     * Record Audio file
     * Doc: http://docs.phonegap.com/en/1.2.0/phonegap_media_capture_capture.md.html#capture.captureAudio
     */
    recordAudio = function (pid) {
    
        /*if( device.platform === 'iPad' ) {
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
            
            function gotFS(fileSystem) {
                alert('got FS');
                fileSystem.root.getFile("myrecording4.wav", {create: true, exclusive: false}, gotFileEntry, onError);
            }
            
            function gotFileEntry(fileEntry) {
                alert('File URI: ' + fileEntry.toURI());
            }   
                
        
        } else {*/
            navigator.device.capture.captureAudio( 
                // success callback
                function(URI) {
                    console.log("recordAudio(): Audio Success");
                    //alert("a "+URI[0].fullPath);
                    
                    adf.mf.api.invokeMethod("mobile.classes.FetchJavascript", "recordAudioSuccessCallback", URI[0].fullPath, pid, 
                        // success callback
                        function() {
                        //alert("b");
                            console.log("recordAudio(): Success callback Success");
                        }, 
                        // error callback
                        function() {
                        //alert("c");
                            console.log("recordAudio(): Success callback Error");
                        }
                    );
                },
                // error callback
                function(err) {
                //alert("d "+err.message);
                    console.log("recordAudio(): Audio Error: "+err);
                    adf.mf.api.invokeMethod("mobile.classes.FetchJavascript", "recordAudioErrorCallback", 
                        // success callback
                        function() {
                        //alert("e");
                            console.log("recordAudio(): Error callback Success");
                        }, 
                        // error callback
                        function() {
                        //alert("f");
                            console.log("recordAudio(): Error callback Error");
                        }
                    );
                }, 
                {limit : 1, duration: 10}
            );
        //} 
        
        
    };
    
    // This method uses PhoneGap and calls the getPicture method to get a picture from the photo library
    chooseImage = function (pid) {
        navigator.camera.getPicture(
            // success callback
            function(URI) {
                console.log("chooseImage():Image Success");
                adf.mf.api.invokeMethod("mobile.classes.FetchJavascript", "chooseImageSuccessCallback", URI, pid,
                    // success callback
                    function() {
                        console.log("chooseImage(): Success callback Success");
                    }, 
                    // error callback
                    function() {
                        console.log("chooseImage(): Success callback Error");
                    }
                );
            },
            // error callback
            function(err) {
                console.log("chooseImage(): Image Error: "+err);
                adf.mf.api.invokeMethod("mobile.classes.FetchJavascript", "chooseImageErrorCallback", 
                    // success callback
                    function() {
                        console.log("chooseImage(): Error callback Success");
                    }, 
                    // error callback
                    function() {
                        console.log("chooseImage(): Error callback Error");
                    }
                );
            }, 
            {quality : 50, destinationType : navigator.camera.DestinationType.DATA_URL, 
            sourceType : navigator.camera.PictureSourceType.PHOTOLIBRARY, targetHeight: 200});
    };
    
    /**
     * Feature navigation
     * @param arguments[0] control flow name
     */
    featureNavigation = function() {
        adf.mf.api.amx.doNavigation(arguments[0]);
    }
    
    /**
     * Show localize message alert
     */
    messageAlert = function () {
        adf.mf.api.amx.addMessage(arguments[0], arguments[1], null, null);
    }
    
    messageLog = function () {
        //alert(arguments[0]);
        console.log("LOG: " + arguments[0]);
    }
    
    /**
     * Set sketch color, size and tool
     */
    setSketch = function () {
        try {
            var drawElement = document.getElementById("simple_sketch");
            if (drawElement == null)
                 alert("drawElement not found");
            var canvas = $(drawElement);
            canvas.sketch().set(arguments[0], arguments[1]); // tool
            canvas.sketch().set(arguments[2], arguments[3]); // color
            canvas.sketch().set(arguments[4], arguments[5]); // size
            
            // set draw style viewer
            var drawStyle = document.getElementById("drawStyle");
            if (drawStyle == null)
                 alert("drawStyle not found");
            var dc = $(drawStyle);
            
            // marker tool
            if (arguments[1] == "marker") {
                dc.css('background-color', arguments[3]);
                
            // eraser tool
            } else {
                dc.css('background-color', 'transparent');
            }
            
            // size of line
            switch(arguments[5]) {
                case "5" :
                    dc.css({"min-width":"16px","min-height":"16px","top":"10px"});
                    break;
                case "10" :
                    dc.css({"min-width":"26px","min-height":"26px","top":"5px"});
                    break;
                case "25" :
                    dc.css({"min-width":"36px","min-height":"36px","top":"0px"});
                    break;
                default :
                    dc.css({"min-width":"36px","min-height":"36px","top":"0px"});
                    break;
            }
            
            
            
        } catch (problem) {
            alert("Problem with verbatim code: " + problem);
        }
    }
    
    downloadSketch = function () {
        try {
            var drawElement = document.getElementById("simple_sketch");
            if (drawElement == null)
                 alert("drawElement not found");
            var canvas = $(drawElement);
            canvas.sketch().download("png", arguments[0]); // download
            
        } catch (problem) {
            alert("Problem with verbatim code: " + problem);
        }
    }
    
    clearSketch = function () {
        try {
            var drawElement = document.getElementById("simple_sketch");
            if (drawElement == null)
                 alert("drawElement not found");
            var canvas = $(drawElement);
            canvas.sketch().clear(); // clear
            
        } catch (problem) {
            alert("Problem with verbatim code: " + problem);
        }
    }

})();